//
//  UserViewController.m
//  HuiPinZhiJia
//
//  Created by MS on 16/8/29.
//  Copyright © 2016年 MS. All rights reserved.
//

#import "UserViewController.h"
#import "SuperNav.h"
#import "UserCollectionViewCell.h"
#import "collectioncellBtn.h"
#import "headerCell.h"
#import "RegisterViewController.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "PersonalModel.h"
#import "UIImageView+WebCache.h"
#import "PersonalController.h"
@interface UserViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,headerCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property (nonatomic,strong)NSArray *nameLabel;
@property (nonatomic,strong)NSArray *nameBtn;
@property (nonatomic,strong)PersonalModel *personal;
@property (nonatomic,strong)NSString *url;
@end

@implementation UserViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"个人中心";
    [self.collectionView reloadData];
    _nameLabel = @[@"未付款",@"全部订单",@"收货地址",@"资金管理",@"个人资料",@"修改密码",@"客户服务",@"我的分享",@"我的标签",@"我的红包",@"缺货登记",@"我的团购"];
    _nameBtn = @[@"我的收藏",@"我的评论",@"浏览记录"];
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:0.41 green:0.79 blue:1.00 alpha:1.00]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],UITextAttributeFont : [UIFont boldSystemFontOfSize:18]}];
    
    [self createCollection];
    // Do any additional setup after loading the view.
}

- (void)createCollection
{
    _flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _flowLayout.minimumInteritemSpacing = 0;//cell之间左右的
    _flowLayout.minimumLineSpacing = 0;//cell上下之间的间距
//    _flowLayout.sectionInset = UIEdgeInsetsMake(10, 0, 0, 0);//section 之间的间距
    _flowLayout.headerReferenceSize = CGSizeMake(screenWidth, 100);
    
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0,screenWidth, screenHeight - 66) collectionViewLayout:_flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"UserCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"user"];
    [_collectionView registerNib:[UINib nibWithNibName:@"collectioncellBtn" bundle:nil] forCellWithReuseIdentifier:@"btn"];
    [_collectionView registerNib:[UINib nibWithNibName:@"headerCell" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.view addSubview:_collectionView];

}

#pragma mark UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 12;
    }else{
        return 3;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        static NSString *cellId = @"user";
        UserCollectionViewCell *cell = [_collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
        cell.headLab.text = _nameLabel[indexPath.row];
        cell.headImg.image = [UIImage imageNamed:@"placeHolder.jpg"];
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00].CGColor;
        return cell;
    }else if(indexPath.section == 1)
    {
          static NSString *celID = @"btn";
        collectioncellBtn * cell1 = [_collectionView dequeueReusableCellWithReuseIdentifier:celID forIndexPath:indexPath];
        cell1.titleBtn.text = _nameBtn[indexPath.row];
        cell1.layer.borderWidth = 1;
        cell1.layer.borderColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00].CGColor;
        return cell1;
    }
    return nil;
}

#pragma mark UICollectionViewFlowLayout delegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return (CGSize){screenWidth/4,110};
    }else
    {
        return (CGSize){screenWidth/3,30};
    }
    return CGSizeZero;
}

#pragma mark UIHeaderView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *resuableview = nil;
        static NSString *cellId = @"header";
        if (kind == UICollectionElementKindSectionHeader)
        {
            headerCell *header = (headerCell*)[_collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:cellId forIndexPath:indexPath];
            header.delegate = self;
            resuableview = header;
            
            NSString *token = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"token"]];
            if ((![token isEqualToString:@""])&&(![token isEqualToString:@"(null)"]))
            {
                [[NetWorking sharedManager]getParameters:@{@"token":token} type:[NetWorking sharedManager].userInfo progressValue:^(double value) {
                    
                } success:^(id obj) {
                NSDictionary *dic = [obj objectForKey:@"data"];
                _personal = [[PersonalModel alloc]initWithDictionary:dic error:nil];
                _url = [NSString stringWithFormat:@"http://e.hulianwangdai.com/Public/Upload/Photo/%@",_personal.avatar];
                
                UIImageView *imageView = [[UIImageView alloc]init];
                
                imageView.frame = header.headBtn.bounds;
                    
                [header.headBtn addSubview:imageView];
                [imageView sd_setImageWithURL:[NSURL URLWithString:_url] placeholderImage:[UIImage imageNamed:@"头像"]];
                 
                header.nameLabel.text = _personal.mobile;
                    header.integrationLabel.text = [NSString stringWithFormat:@"%@分",_personal.salt];
                } failure:^(id error) {
                    
                }];
            }else
            {
                [header.headBtn setBackgroundImage:[UIImage imageNamed:@"头像"] forState:UIControlStateNormal];
                header.nameLabel.text = @"未登陆";
                header.integrationLabel.text = @"0积分";
            }

            
           //个人信息界面
            [header handlerPersonalAction:^{
                
                PersonalController *pcl = [[PersonalController alloc]init];
                pcl.model = _personal;
                pcl.url = _url;
                [self.navigationController pushViewController:pcl animated:YES];
            }];
            //退出登录
            [header handlerButtonAction:^{
                
                NSString *token = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"token"]];
                SLLog(@"%@",token);
                if ((![token isEqualToString:@""])&&(![token isEqualToString:@"(null)"]))
                {
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您确定退出登录么？" preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction *makeSureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [self.collectionView reloadData];
                        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"token"];                    }];
                    
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    }];
                    
                    [alertController addAction:cancelAction];
                    [alertController addAction:makeSureAction];
                    
                    [self presentViewController:alertController animated:YES completion:^{
                       
                    }];

                }else
                {
                    MBProgressHUD *HUD = [(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:@"请先登录"];
                    [HUD hide:YES afterDelay:0.5];
                }
                            }];
            if (indexPath.section == 1)
            {
                resuableview.hidden= YES;
            }
        }
    return resuableview;

 }
#pragma mark 登录 delegate
- (void)Jump:(UIButton *)button
{
    NSString *token = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]];
    if ((![token isEqualToString:@""])&&(![token isEqualToString:@"(null)"])) {
        
    }else
    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        RegisterViewController *rgv = [storyboard instantiateViewControllerWithIdentifier:@"register"];
        [self.navigationController pushViewController:rgv animated:YES];
    }
}

#pragma mark 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SLLog(@"你点击了第%ld组 第%ld行",indexPath.section,indexPath.row);
}

- (void)selectAtIndex:(UIButton *)sender
{
    if (sender.tag == 10000)
    {
        NSString *token = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]];
        if (([token isEqualToString:@""])||([token isEqualToString:@"null"]))
        {
            
        }else
        {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            RegisterViewController *rgv = [storyboard instantiateViewControllerWithIdentifier:@"register"];
            [self.navigationController pushViewController:rgv animated:YES];
        }
    }else
    {
    
    }
}

//最小列间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
//{
//    return 0;
//}
//
////最小行间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
//{
//    return 0;
//}
//每组间的间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0)
    {
        return (UIEdgeInsets){10,0,10,0};
    }else
    {
        return (UIEdgeInsets){-100,0,10,0};
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
